package com.mobi.Survey.map;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.view.View;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.mobi.Survey.lib.activities.AbstractScreen;
import com.mobi.Survey.lib.activities.Messages;
import com.mobi.Survey.lib.utils.Helper;

public class MapContainer extends Container implements OnInfoWindowClickListener, OnMarkerClickListener {
	private GoogleMap map;
	private Map<Marker, MapMarker> markerMap = new HashMap<Marker, MapMarker>();
	private static List<MapMarker> mapMarers;

	public MapContainer(AbstractScreen activity) {
		this.activity = activity;
		this.container = activity.findViewById(R.id.containerMap);
		SupportMapFragment mapFragment = (SupportMapFragment) activity.getSupportFragmentManager().findFragmentById(
				R.id.map);
		map = mapFragment.getMap();
	}

	private String ellipsizeBy(String str, int afterLength) {
		if (null != str && str.length() > afterLength) {

			return str.substring(0, afterLength).concat("...");
		}
		return "";
	}

	@Override
	public void setupViews() {

		if (null != map) {
			map.setOnInfoWindowClickListener(this);
			map.setOnMarkerClickListener(this);
			try {
				// map.setMyLocationEnabled(true);
			} catch (Exception e) {
				// TODO: handle exception
			}

			mapMarers = MapLogin.getMapPoints();
			map.setInfoWindowAdapter(new InfoWindowAdapter() {

				@Override
				public View getInfoWindow(Marker marker) {
					View v = activity.getLayoutInflater().inflate(R.layout.info_window, null);

					((TextView) v.findViewById(R.id.tvTitle)).setText(ellipsizeBy(marker.getTitle(), 22));
					((TextView) v.findViewById(R.id.tvSnippet)).setText(marker.getSnippet());
					return v;

				}

				@Override
				public View getInfoContents(Marker marker) {

					return null;
				}
			});
			new CreateMarkerTask().execute();

		}

	}

	@Override
	public boolean onMarkerClick(Marker marker) {

		// marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
		return false;
	}

	@Override
	public void onInfoWindowClick(Marker marker) {

		MapMarker mapMarker = markerMap.get(marker);

		AbstractScreen.setMapTabId(this.activity, 22);
		MapHelper.executeSurveyDownloadTask(activity, mapMarker);

	}

	private class CreateMarkerTask extends AsyncTask<Integer, Integer, Integer> {
		ProgressDialog progressDialog = null;

		@Override
		protected void onPreExecute() {

			super.onPreExecute();
			try {
				progressDialog = ProgressDialog.show(activity, "", Messages.FETCHING_SURVEY);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		protected void onPostExecute(Integer result) {

			super.onPostExecute(result);
			Bitmap bm = BitmapFactory.decodeResource(activity.getApplicationContext().getResources(),
					R.drawable.map_pointer);
			Bitmap workingBitmap = Bitmap.createBitmap(bm);

			Paint p = new Paint();
			p.setColor(activity.getResources().getColor(R.color.map_heading));
			p.setTextSize(40);
			if (null != mapMarers && mapMarers.size() > 0) {
				int i = 1;
				for (MapMarker mapMarker : mapMarers) {
					LatLng latLng = null;

					if (mapMarker.isCalculatedLatLng()) {
						latLng = mapMarker.getCalculatedLatLng();
					} else {
						latLng = new LatLng(Helper.toDouble(mapMarker.getLatitude()), Helper.toDouble(mapMarker
								.getLongitude()));
					}

					Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
					Canvas canvas = new Canvas(mutableBitmap);
					int offset = 35;
					String drawText = "" + i;
					if (drawText.length() == 2) {
						offset = 20;
					}
					if (drawText.length() == 3) {
						offset = 10;
					}
					canvas.drawText(drawText, offset, 60, p);
					i++;
					MarkerOptions options = new MarkerOptions().position(latLng).icon(
							BitmapDescriptorFactory.fromBitmap(mutableBitmap));

					Marker marker = map.addMarker(options.position(latLng).title(mapMarker.getDescription())
							.snippet(mapMarker.getUserId()));

					markerMap.put(marker, mapMarker);

				}

				map.moveCamera(CameraUpdateFactory.newLatLngZoom(
						new LatLng(Helper.toDouble(mapMarers.get(0).getLatitude()), Helper.toDouble(mapMarers.get(0)
								.getLongitude())), 20));

				// Zoom in, animating the camera.
				map.animateCamera(CameraUpdateFactory.zoomTo(10), 1800, null);
			}
			progressDialog.dismiss();

		}

		@Override
		protected Integer doInBackground(Integer... arg0) {

			return null;
		}
	}

	@Override
	public void refresh() {

		setupViews();
	}

}
